package com.atguigu.ggkt.vod.service.impl;

import com.atguigu.ggkt.model.vod.Chapter;
import com.atguigu.ggkt.model.vod.Video;
import com.atguigu.ggkt.vo.vod.ChapterVo;
import com.atguigu.ggkt.vo.vod.VideoVo;
import com.atguigu.ggkt.vod.mapper.ChapterMapper;
import com.atguigu.ggkt.vod.service.ChapterService;
import com.atguigu.ggkt.vod.service.VideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author lxx
 * @since 2022-06-30
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> getTreeList(Long courseId) {
        // 1.获取章节列表
        List<Chapter> chapterList = query().eq("course_id", courseId).list();
        // 2.遍历章节列表，将小节封装到列表中,并返回chapterVoList
        List<ChapterVo> chapterVoList = chapterList.stream().map(chapter -> {
            // 2.1.将chapter属性裁剪到chapterVo中
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            // 2.2.获取章节id
            Long chapterId = chapter.getId();
            // 2.3.获取小节列表
            List<Video> videoList = videoService.query().eq("chapter_id", chapterId).list();
            // 2.4.将每个小节裁剪成videoVo对象
            List<VideoVo> videoVoList = videoList.stream().map(vide -> {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(vide, videoVo);
                return videoVo;
            }).collect(Collectors.toList());
            // 2.5.将videoVoList赋值给chapterVo
            chapterVo.setChildren(videoVoList);
            // 3.返回
            return chapterVo;
        }).collect(Collectors.toList());
        return chapterVoList;
    }

    @Override
    public void deleteChapterAndVideo(Long id) {
        // 1.获取小节列表
        List<Video> videoList = videoService.query().eq("chapter_id", id).list();
        // 2.删除小节和小节视频
        videoList.forEach(video -> {
            videoService.removeVideoAndVod(video.getId());
        });
        // 3.删除章节
        removeById(id);
    }
}
